<template>
  <view class="inbound-create-container">
    <uni-forms ref="form" :model="formData" :rules="rules" class="form-container">
      <uni-forms-item label="项目名称" name="projectId" class="form-item">
        <uni-data-select v-model="formData.projectId" :localdata="project_list" placeholder="可选，不选则不关联项目" @change="handleProjectChange" />
      </uni-forms-item>
      <uni-forms-item label="出行方式" name="transportType" class="form-item">
        <uni-data-select v-model="formData.transportType" :localdata="transport_type" />  
      </uni-forms-item>
      
      <!-- 只有当出行方式为"公司车辆"时才显示备选车辆 -->
      <uni-forms-item v-if="formData.transportType === '1'" label="备选车辆" name="bookLicensePlate" class="form-item">
        <uni-data-select v-model="formData.bookLicensePlate" :localdata="car_list" />
      </uni-forms-item>
               
      <uni-forms-item label="取货司机" name="driver" class="form-item">
        <uni-data-select v-model="formData.driver" :localdata="driver_list" />
      </uni-forms-item>

      <uni-forms-item label="客户" name="customer" class="form-item">
        <uni-data-select v-model="formData.companyId" :localdata="customers" />
      </uni-forms-item>
        <!-- 辅料物品列表 -->
        <view class="auxiliary-materials">
        <view class="section-header">
          <text >辅料物品</text>
          <button class="add-btn" size="mini" type="primary" @click="addAuxiliaryItem">添加物品</button>
        </view>
        
        <view v-for="(item, index) in formData.storeOrderAuxiliaryList" :key="index" class="auxiliary-item">
          <view class="item-header">
            <text class="item-title">物品 {{index + 1}}</text>
            <text class="delete-btn" @click="removeAuxiliaryItem(index)">删除</text>
          </view>
          
          <uni-forms-item :label="'类别'" :name="'auxiliaryItems.' + index + '.auxiliaryType'" class="form-item">
            <uni-data-select v-model="item.auxiliaryType" :localdata="auxiliary_type" placeholder="请选择类别" />
          </uni-forms-item>
          
          <uni-forms-item :label="'辅料名称'" :name="'auxiliaryItems.' + index + '.name'" class="form-item">
            <uni-easyinput v-model="item.name" placeholder="请输入辅料名称" />
          </uni-forms-item>
          
          <uni-forms-item :label="'型号'" :name="'auxiliaryItems.' + index + '.model'" class="form-item">
            <uni-easyinput v-model="item.model" placeholder="请输入型号" />
          </uni-forms-item>
          
          <uni-forms-item :label="'规格'" :name="'auxiliaryItems.' + index + '.specifications'" class="form-item">
            <uni-easyinput v-model="item.specifications" placeholder="请输入规格" />
          </uni-forms-item>

          <uni-forms-item :label="'单位'" :name="'auxiliaryItems.' + index + '.unit'" class="form-item">
            <uni-easyinput v-model="item.unit" placeholder="请输入单位" />
          </uni-forms-item>
          
          <uni-forms-item :label="'数量'" :name="'auxiliaryItems.' + index + '.num'" class="form-item">
            <uni-number-box v-model="item.num" :min="1" />
          </uni-forms-item>
        </view>
      </view>
      
      <uni-forms-item label="备注" name="remark" class="form-item">
        <uni-easyinput v-model="formData.remark" type="textarea" placeholder="请输入备注信息" />
      </uni-forms-item>
    </uni-forms>
    
    <view class="button-group">
      <button class="submit-btn" @click="submitForm">保存订单</button>
      <button class="reset-btn" @click="resetForm">重置</button>
    </view>
  </view>
</template>

<script>
import { addOrder } from "@/api/mes/order"
import { listCar } from "@/api/mes/car"
import { getDicts } from "@/api/system/dict/data" // 引入字典API
import { getProjectAll } from "@/api/mes/project"
import { listDriver } from "@/api/mes/projectExtend"
import { listCompany} from "@/api/mes/company"
export default {
  data() {
    return {
      maxCot:100,
      projectName: null,
      car_list: [],
      customers: [
      ],
      project_list: [],
      project_detail: {},
      // 字典数据
      transport_type: [],
      order_status: [],
      driver_list: [],
      auxiliary_type : [],
      // 辅料类别选项
      formData: {
        storeOrderAuxiliaryList: [] // 初始化辅料物品列表
      },
      rules: {
        bookLicensePlate: {
          rules: [{ required: true, errorMessage: '请选择备选车辆' }]
        },
        driver: {
          rules: [{ required: true, errorMessage: '请选择司机' }]
        },
      }
    }
  },
  onLoad() {
    this.getProjectList();
    this.getCarList();
    this.getDictData(); // 获取字典数据
    this.getDriverList();
    this.getCostomerSelect();
    // 初始化表单数据
    this.formData = {
      storeOrderAuxiliaryList: [],
      storeOrderCargoList: []
    };
  },
  methods: {
    handleProjectChange(value) {
      // 如果选择了"通用"选项（值为0），则将projectId设为null
      if (value === 0) {
        this.formData.projectId = null;
      }
    },
    getDriverList() {
      listDriver().then(response => {
        this.driver_list = response.data.map(driver => ({
          value: driver.userId.toString(),
          text: driver.nickName
        }));
      }); 
    },
    getCostomerSelect() {
      listCompany().then(response => {
        this.customers = response.rows.map(customers => ({
            value: customers.companyId.toString(),
            text: customers.companyName
          }));
      });
    },
    // 添加辅料物品
    addAuxiliaryItem() {
      if (!this.formData.storeOrderAuxiliaryList) {
        this.formData.storeOrderAuxiliaryList = [];
      }
      
      this.formData.storeOrderAuxiliaryList.push({
        auxiliaryType: '',
        name: '',
        model: '',
        specifications: '',
        unit: '',
        num: 1
      });
    },
    
    // 删除辅料物品
    removeAuxiliaryItem(index) {
      this.formData.storeOrderAuxiliaryList.splice(index, 1);
    },
    
    // 添加手动验证辅料物品的方法
    validateAuxiliaryItems() {
      if (!this.formData.storeOrderAuxiliaryList || this.formData.storeOrderAuxiliaryList.length === 0) {
        return true; // 如果没有辅料物品，则验证通过
      }
      
      let isValid = true;
      
      this.formData.storeOrderAuxiliaryList.forEach((item, index) => {
        if (!item.name) {
          uni.showToast({
            title: `物品 ${index + 1} 的辅料名称不能为空`,
            icon: 'none'
          });
          isValid = false;
        }
        
        if (!item.num || item.num <= 0) {
          uni.showToast({
            title: `物品 ${index + 1} 的数量必须大于0`,
            icon: 'none'
          });
          isValid = false;
        }
      });
      
      return isValid;
    },
    submitForm() {
      this.$refs.form.validate().then(res => {
        // 手动验证辅料物品
        if (!this.validateAuxiliaryItems()) {
          return;
        }
        
        // 显示加载提示
        uni.showLoading({
          title: '提交中...',
          mask: true
        });
        this.formData.orderType = 3;
        // 提交数据
        // console.log("提交表达内容",this.formData)
        addOrder(this.formData)
          .then(response => {
            if (response.code === 200) {
              uni.showToast({
                title: '提交成功',
                icon: 'success'
              });
              setTimeout(() => {
                // 使用navigateBack返回上一页
                uni.navigateBack({
                  delta: 1,
                  success: function() {
                    // 获取当前页面栈
                    const pages = getCurrentPages();
                    // 获取上一页实例
                    const prevPage = pages[pages.length - 1];
                    // 调用上一页的刷新方法
                    if (prevPage && prevPage.$vm && typeof prevPage.$vm.getList === 'function') {
                      prevPage.$vm.getList();
                    }
                  }
                });
              }, 100);
            } else {
              throw new Error(response.msg || '提交失败');
            }
          })
          .catch(error => {
            console.error('提交失败：', error);
            uni.showToast({
              title: error.message || '提交失败，请重试',
              icon: 'error'
            });
          })
          .finally(() => {
            uni.hideLoading(); // 确保在任何情况下都关闭loading
          });
      }).catch(err => {
        // 表单验证失败
        console.error('表单验证失败：', err);
        uni.hideLoading(); // 表单验证失败时也要关闭loading
        uni.showToast({
          title: '请检查必填项',
          icon: 'none'
        });
      });
    },
    resetForm() {
      // 重置表单数据
      this.formData = {
      
      }
      // 重置表单校验状态
      if (this.$refs.form && typeof this.$refs.form.resetFields === 'function') {
        this.$refs.form.resetFields()
      } else {
        // 针对小程序环境，手动清除校验状态
        this.$nextTick(() => {
          if (this.$refs.form) {
            this.$refs.form.clearValidate()
          }
        })
      }
      // 提示用户
      uni.showToast({
        title: '已重置',
        icon: 'none'
      })
    },
    getProjectList() {
      getProjectAll().then(response => {
        // 添加一个通用选项
        const projectList = [
          {
            value: 0,
            text: "通用"
          }
        ];
        
        // 将API返回的项目数据添加到列表中
        const apiProjects = response.rows.map(project => ({
              value: project.projectId,
              text: project.projectName,
            }));
        
        // 合并通用选项和API返回的项目列表
        this.project_list = projectList.concat(apiProjects);
      });
    },
    getCarList() {
      listCar().then(response => {
        this.car_list = response.data.map(car => ({
              value: car.carId,
              text:  car.carNo,
            }));
      });
    },
    getDictData() {
      getDicts('transport_type').then(response => {
        this.transport_type = response.data.map(item => ({
          value: item.dictValue,
          text: item.dictLabel
        }));
      });
      getDicts('order_status').then(response => {
        this.order_status = response.data
      });
      getDicts('auxiliary_type').then(response => {
        this.auxiliary_type = response.data.map(item => ({
          value: item.dictValue,
          text: item.dictLabel
        }));
      });
    },
  }
}
</script>

<style lang="scss" scoped>
.inbound-create-container {
  padding: 30rpx;
  background-color: #f8f8f8;
  min-height: 100vh;
  
  .form-container {
    background-color: #fff;
    border-radius: 16rpx;
    padding: 20rpx;
    margin-bottom: 30rpx;
    
    .form-item {
      margin-bottom: 24rpx;
      
      :deep(.uni-forms-item__label) {
        font-size: 28rpx;
        color: #333;
        padding: 0 12rpx;
      }
      
      :deep(.uni-easyinput__content) {
        min-height: 72rpx;
        background-color: #f8f8f8;
        border-radius: 8rpx;
        
        input {
          font-size: 28rpx;
        }
      }
      
      :deep(.uni-data-select) {
        .uni-select--mask {
          background-color: #f8f8f8;
          border-radius: 8rpx;
        }
        
        .uni-select__input-text {
          font-size: 28rpx;
        }
      }
    }
  }
  
  .products-container {
    .product-item {
      margin: 20rpx 0;
      padding: 20rpx;
      background-color: #f8f8f8;
      border-radius: 8rpx;
    }
  }
  
  // 辅料物品样式
  .auxiliary-materials {
    margin: 30rpx 0;
    
    .section-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-bottom: 20rpx;
      
      .section-title {
        font-size: 32rpx;
        font-weight: bold;
        color: #333;
      }
      
      .add-btn {
        font-size: 24rpx;
        padding: 6rpx 20rpx;
      }
    }
    
    .auxiliary-item {
      margin: 20rpx 0;
      padding: 20rpx;
      background-color: #f8f8f8;
      border-radius: 12rpx;
      box-shadow: 0 2rpx 6rpx rgba(0, 0, 0, 0.05);
      
      .item-header {
        display: flex;
        justify-content: space-between;
        align-items: center;
        margin-bottom: 16rpx;
        
        .item-title {
          font-size: 28rpx;
          font-weight: bold;
          color: #333;
        }
        
        .delete-btn {
          font-size: 26rpx;
          color: #ff5a5f;
          padding: 4rpx 12rpx;
        }
      }
    }
  }
  
  .button-group {
    margin-top: 40rpx;
    padding: 0 20rpx;
    
    .submit-btn {
      width: 100%;
      height: 88rpx;
      line-height: 88rpx;
      background-color: #007AFF;
      color: #fff;
      font-size: 32rpx;
      border-radius: 44rpx;
      margin-bottom: 20rpx;
    }
    
    .reset-btn {
      width: 100%;
      height: 88rpx;
      line-height: 88rpx;
      background-color: #F1F1F1;
      color: #333;
      font-size: 32rpx;
      border-radius: 44rpx;
    }
  }
}
</style>